package com.mairuide.bill.methodsanalysis.commonDayAndAddress;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mairuide._frame.base.BaseController;
import com.mairuide._frame.base.ModuleCode;
import com.mairuide._frame.base.PageSupport;
import com.mairuide._frame.utils.StringUtils;
import com.mairuide.bill.DealFlow;
import com.mairuide.bill.methodsanalysis.CommonStatistics;
import com.mairuide.bill.methodsanalysis.CommonStatisticsParams;
import com.mairuide.bill.methodsanalysis.CommonStatisticsService;
import com.mairuide.bill.utils.ExcelUtil;
import com.mairuide.datalog.ActionType;
import com.mairuide.datalog.DataOperationLogService;
import com.mairuide.datalog.ModuleFlag;
import com.mairuide.datalog.SystemFlag;
import com.mairuide.entity.PageResult;
/**
 * 同天同地点
 * @author mh
 *
 */
@Controller
@RequestMapping("/commonDayAndAddress")
public class CommoDayAndAddressController  extends BaseController {

	@Resource
	private CommonStatisticsService commonStatisticsService;
	@Resource
	private DataOperationLogService dataOperationLogService;
	
	/**
	 * 常用战法分析同天同地点查询入口
	 * @param model
	 * @param pagesupport
	 * @return
	 */
	@ModuleCode(pValue = "billskill", value = "commonDayAndAddressMC")
	@RequestMapping(value = "/commonDayAndAddressInit", method = RequestMethod.GET)
	public Object billcash(ModelMap model, PageSupport pagesupport) {
		model.addAttribute("menu", "commonDayAndAddressInit");
		return "/methodsanalysis/commonDayAndAddress";
	}
	
	/**
	 * 常用战法分析同天同地点查询
	 * @param model
	 * @param pagesupport
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/getCommonDayAndAddress")
	@ResponseBody
	public Object commonAccount(String sortName,String sortOrder,CommonStatisticsParams csp,  PageSupport pagesupport) {
		String caseId = csp.getCaseId();
		Map<String, Object> result = new HashMap<String,Object>();
		if(StringUtils.isNotEmpty(caseId)) {
			csp.setCaseId(caseId);
			if(StringUtils.isNotEmpty(csp.getShowType()) && csp.getShowType().equals("1")) {
				PageResult page = commonStatisticsService.findCommonDayAndAddressByPageEasyUi(csp);
				result.put("total", page.getTotal());
				result.put("rows", page.getRows());
			}else if(StringUtils.isNotEmpty(csp.getShowType()) && csp.getShowType().equals("0")) {
				List<CommonStatistics> css = commonStatisticsService.findCommonDayAndAddressAll(csp);
				if(css != null && !css.isEmpty()) {
					result.put("total", css.size());
					if (css.size() > 10) {
						Collections.sort(css, new SortList());
						List<CommonStatistics> rows = css.subList(0, 10);
						result.put("rows", rows);
					} else {
						result.put("rows", css);
					}
				}else {
					result.put("total", 0);
					result.put("rows", new ArrayList<Object>());
				}
			}
			
		}else {
			result.put("total", 0);
			result.put("rows", new ArrayList<Object>());
		}
		return result;
	}

	@SuppressWarnings("rawtypes")
	class SortList implements Comparator {
		public int compare(Object o1, Object o2) {
			CommonStatistics w1 = (CommonStatistics) o1;
			CommonStatistics w2 = (CommonStatistics) o2;
			return w2.getOccurrences().compareTo(w1.getOccurrences());
		}
	}

	/**
     * 同天同地点导出
	 * @throws Exception 
     */
    @RequestMapping("/exportCommonDayAndAddress")
    @ResponseBody
    public void exportFile(HttpServletResponse response, CommonStatisticsParams csp) throws Exception {

        // 生成导出excel名称
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = "同天同地点" + dateFormat.format(date);

        //设置导出Excel标题
        String[] titles = { "共同日期", "共同交易机构号", "共同交易机构名称", "出现次数", "出现对象", "总金额"};

        //遍历导出Excel的内容
        List<CommonStatistics> list = commonStatisticsService.findCommonDayAndAddressAll(csp);
        List<Map<Integer, String>> lists = new ArrayList<Map<Integer, String>>();
        if(null != list && !list.isEmpty()) {
        	for (CommonStatistics cs : list) {
        		Map<Integer, String> map = new HashMap<Integer, String>();
        		//共同交易日期
        		map.put(0, cs.getAriseDate() == null?"":cs.getAriseDate().toString());
        		//共同交易机构号
        		map.put(1, cs.getOrganizationNumber() == null?"":cs.getOrganizationNumber().toString());
        		//共同交易机构名称
        		map.put(2, cs.getOrganizationName() == null?"":cs.getOrganizationName().toString());
        		//交易出现次数
        		map.put(3, cs.getOccurrences() == null ? "" : cs.getOccurrences().toString());
        		//出现对象
        		map.put(4, cs.getAriseObject() == null ? "" : cs.getAriseObject().toString());
        		//总金额
        		map.put(5, cs.getSumMoney() == null ? "" : cs.getSumMoney().toString());
        		//把map集合添加到lists集合
        		lists.add(map);
        	}
        }

		//插入导出日志
        dataOperationLogService.save(null, super.getLoginUser(), new DealFlow(), new DealFlow(), SystemFlag.ZD, ModuleFlag.COMMONDAYANDADDRESS, ActionType.EXPORT);
        // 把导出的内容写入到流里面
        byte[] content = ExcelUtil.writeExcel(titles, lists);
        InputStream is = new ByteArrayInputStream(content);

        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
    }
	
}
